from fastapi import APIRouter, HTTPException
from app.models.response import HealthResponse
from app.services.colorizer import colorization_service
from app.services.storage import storage_service
from app.services.queue import task_queue
import logging

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/health", tags=["health"])


@router.get("/", response_model=HealthResponse)
async def health_check():
    """Health check endpoint"""
    services = {}
    
    # Check model service
    try:
        if colorization_service.pipeline is not None:
            services["model"] = "loaded"
        else:
            services["model"] = "not_loaded"
    except Exception as e:
        services["model"] = f"error: {str(e)}"
    
    # Check storage service
    try:
        services["storage"] = "connected"
    except Exception as e:
        services["storage"] = f"error: {str(e)}"
    
    # Check queue service
    try:
        queue_stats = await task_queue.get_queue_stats()
        services["queue"] = "connected"
        services["queue_stats"] = queue_stats
    except Exception as e:
        services["queue"] = f"error: {str(e)}"
    
    # Determine overall health
    status = "healthy"
    for service_status in services.values():
        if isinstance(service_status, str) and service_status.startswith("error"):
            status = "unhealthy"
            break
    
    return HealthResponse(
        status=status,
        version="1.0.0",
        services=services
    )


@router.get("/ready")
async def readiness_check():
    """Kubernetes readiness probe"""
    health = await health_check()
    if health.status == "healthy":
        return {"status": "ready"}
    else:
        raise HTTPException(status_code=503, detail="Service not ready")


@router.get("/live")
async def liveness_check():
    """Kubernetes liveness probe"""
    return {"status": "alive"}
